// =================================================================================================
//
//	CopyEngine Framework
//	Copyright 2012 Eran. All Rights Reserved.
//
//	This program is free software. You can redistribute and/or modify it
//	in accordance with the terms of the accompanying license agreement.
//
// =================================================================================================

package manger
{
    import data.vo.LayoutItemVo;
    import data.vo.LayoutItemVoManger;

    import flash.events.Event;
    import flash.filesystem.File;
    import flash.filesystem.FileMode;
    import flash.filesystem.FileStream;

    import gui.fileSetting.FileSettingPanel;
    import gui.itemSetting.LayoutItemSettingPanel;
    import gui.itemView.LayoutItemViewPanel;
    import gui.viewport.LayoutEditViewport;
    import gui.viewport.ViewportOperator;

    import utils.MessageBox;

    public class LogicManger
    {
        private var mViewportOperator:ViewportOperator;
        private var mViewport:LayoutEditViewport;
        private var mItemSettingPanel:LayoutItemSettingPanel;
        private var mItemViewPanel:LayoutItemViewPanel;
        private var mFileSettingPanel:FileSettingPanel;

        private var mCurrentFile:File;

        public function LogicManger()
        {
        }

        //==================================
        //== Initialize & Dispose
        //==================================

        public function initialize(_viewport:LayoutEditViewport,
                                   _viewportOperator:ViewportOperator,
                                   _itemSettingPanel:LayoutItemSettingPanel,
                                   _itemViewPanel:LayoutItemViewPanel,
                                   _fileSettingPanel:FileSettingPanel):void
        {
            mViewport = _viewport;
            mViewportOperator = _viewportOperator;
            mItemSettingPanel = _itemSettingPanel;
            mItemViewPanel = _itemViewPanel;
            mFileSettingPanel = _fileSettingPanel;

            mItemSettingPanel.hide();
            mItemViewPanel.show();
        }

        //==================================
        //== Public Function
        //==================================


        //==================
        //==视口相关
        //==================

        /**
         * 点击更改屏幕的大小
         */
        public function onClickChangeScreenSizeConfirmBtn(_screenWidth:int, _screenHeight:int):void
        {
            mViewport.changeScreenSize(_screenWidth, _screenHeight);
            MessageBox.instance.showMsg("屏幕尺寸更改为: " + _screenWidth + " x " + _screenHeight);
        }

        /**
         * 将视口切换为原始大小
         */
        public function onClickOriginalViewportSizeBtn():void
        {
            mViewport.changeScreenToOriginalSize();
        }

        /**
         * 将视口切换为适配GUI显示区域(全部可以显示下)
         */
        public function onClickFixViewportSizeBtn():void
        {
            mViewport.changeScreenFitForScreen();
        }

        //===================
        //==ItemViewPanel相关
        //===================

        public function onClickCreateNewLayoutItem():void
        {
            var newItem:LayoutItemVo = LayoutItemVoManger.instance.createNewLayoutItem();
            mItemViewPanel.hide();
            mItemSettingPanel.show(newItem);
        }

        public function onClickDeleteLayoutItem(_itemID:String):void
        {
            LayoutItemVoManger.instance.deleteLayoutItemByID(_itemID);
            mItemViewPanel.refresh();
        }

        public function onClickEditExistLayoutItem(_itemID:String):void
        {
            var item:LayoutItemVo = LayoutItemVoManger.instance.getLayoutItemByID(_itemID);
            mItemViewPanel.hide();
            mItemSettingPanel.show(item);
        }

        //======================
        //==ItemSettingPanel相关
        //======================

        public function onClickQuitSettingPanel():void
        {
            mItemSettingPanel.hide();
            mItemViewPanel.show();
            mItemViewPanel.refresh();
        }


        //======================
        //==File Setting
        //======================

        /**
         * 点击打开
         */
        public function onClickOpenNewFile():void
        {
            mCurrentFile = new File();
            mCurrentFile.browseForOpen("选择Layout文件");
            mCurrentFile.addEventListener(Event.SELECT, onSelectOpenFile);
        }

        private function onSelectOpenFile(e:Event):void
        {
            var isOpenFileError:Boolean = true;
            try
            {
                var fileStream:FileStream = new FileStream();
                fileStream.open(mCurrentFile, FileMode.READ);
                var jsonString:String = fileStream.readUTFBytes(fileStream.bytesAvailable);
                LayoutItemVoManger.instance.fromJSON(JSON.parse(jsonString));
                fileStream.close();
                isOpenFileError = false;
            } catch (e:Error)
            {
                mCurrentFile = null;
                MessageBox.instance.showMsg("无法打开文件,格式不对或已损坏");
            }

            if (!isOpenFileError)
            {
                MessageBox.instance.showMsg("打开成功!");

                mFileSettingPanel.refresh(mCurrentFile);
                mItemSettingPanel.hide();
                mItemViewPanel.show();
                mItemViewPanel.refresh();
            }
        }


        /**
         * 点击保存
         */
        public function onClickSaveFile():void
        {
            if (mCurrentFile == null)
            {
                mCurrentFile = new File();
                mCurrentFile.browseForSave("选择保存的位置");
                mCurrentFile.addEventListener(Event.SELECT, onSelectSaveFile);
            }
            else
            {
                doSaveFile();
            }
        }

        private function onSelectSaveFile(e:Event):void
        {
            doSaveFile();
        }

        private function doSaveFile():void
        {
            var jsonString:String = LayoutItemVoManger.instance.toJSONString();
            if (jsonString == null)
            {
                MessageBox.instance.showMsg("没有东西,存什么啊?");
            }
            else if (jsonString == "ERROR")
            {
                MessageBox.instance.showMsg("文件 ToJson异常,请联系Eran");
            }
            else
            {
                var isSaveFileError:Boolean = true;
                try
                {
                    mCurrentFile.exists && mCurrentFile.deleteFile();
                    var fileStream:FileStream = new FileStream();
                    fileStream.open(mCurrentFile, FileMode.WRITE);
                    fileStream.writeUTFBytes(jsonString);
                    fileStream && fileStream.close();
                    fileStream = null;
                    isSaveFileError = false;
                } catch (e:Error)
                {
                    MessageBox.instance.showMsg("错误!  无法保存文件");
                }

                if (!isSaveFileError)
                {
                    MessageBox.instance.showMsg("保存成功!");
                    mFileSettingPanel.refresh(mCurrentFile);
                }
            }
        }


    }
}
